package org.biogroovy.io.journaltocs

import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.biogroovy.io.AbsReader;
import org.biogroovy.io.AbsXmlReader
import org.biogroovy.io.IFetcher;
import org.biogroovy.models.Article
import org.biogroovy.models.Author
import org.w3c.dom.Node

/**
 * This class is responsible for reading article information from the JournalTOCs
 * web service.
 *
 */
class JournalTOCSArticleReader extends AbsXmlReader<Article> {
	
	private static final String DATABASE_NAME = "journaltocsarticle";

	@Override
	public void parse(Article article, Node node) {
		article.title = node.title.text();
		article.abs = node.description.text();
		article.doi = node.'dc:identifier'.text();
		article.doi = article.doi.replace("DOI ","");
		article.url = node.link.text();
				
		node.'dc:creator'.each{def currNode ->
			String name = currNode.text();
			Author author = new Author();
			int index = name.indexOf(" ");
			author.firstname = name.substring(0, index);
			author.lastname = name.substring(index+1);
			article.authors.add(author);
		}
	}

	@Override
	public Article read(InputStream inputStream) throws IOException {
		//NO-OP
	}



	@Override
	public List<Article> readList(InputStream inputStream) throws IOException {
		List<Article> articleList = new ArrayList<>();
		
		XmlParser xml = new XmlParser(false,false);
		
		Map nsMap = [
				rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",
				prism:"http://prismstandard.org/namespaces/1.2/basic/",
				dc:"http://purl.org/dc/elements/1.1/",
				mn:"http://usefulinc.com/rss/manifest/",
				content:"http://purl.org/rss/1.0/modules/content/"
			];
		groovy.util.Node result = xml.parse(inputStream);
		
		result.items.each {Node itemNode ->
			Article article = new Article();
			parse(article, itemNode)
			articleList.add(article);
		}
		
		return articleList;
	}

	@Override
	public Article fetch(String id) throws IOException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public URL getUrl(String id, Map<String, String> paramMap) {
		return new URL("http://www.journaltocs.ac.uk/api/journals/${id}?output=articles&user=${paramMap.journaltocs.userid}")
	}

	@Override
	public String getDatabaseName() {
		return DATABASE_NAME;
	}

	@Override
	public List<Article> fetchAll(String id) throws IOException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public IFetcher<Article> getNewInstance() {
		return new JournalTOCSArticleReader();
	}

}
